import { LeftOutline } from "antd-mobile-icons";
import { useNavigate, useLocation } from "react-router-dom";
import { useEffect, useState, useCallback } from "react";
import { Input } from "antd-mobile";
import getApi from "../../result/api";


export default function Chatroom() {
   const navigate = useNavigate();
   // 定义一个函数将时间戳转换成标准时间
   const formatDate = (time) => {
      let date = new Date(time);
      return date.toLocaleString();
   };
   // 定义一个函数将时间戳转换成相对时间
   const relativeDate = (time) => {
      let newtime = new Date(time).getTime();
      let now = new Date().getTime();
      let diff = now - newtime;
      if (diff < 60 * 1000) {
         return "刚刚";
      } else if (diff < 60 * 60 * 1000) {
         return `${Math.floor(diff / 60 / 1000)}分钟前`;
      } else if (diff < 24 * 60 * 60 * 1000) {
         return `${Math.floor(diff / 60 / 60 / 1000)}小时前`;
      } else if (diff < 7 * 24 * 60 * 60 * 1000) {
         return `${Math.floor(diff / 24 / 60 / 60 / 1000)}天前`;
      } else if (diff < 365 * 24 * 60 * 60 * 1000) {
         return `${Math.floor(diff / 7 / 24 / 60 / 60 / 1000)}周前`;
      } else {
         return `${Math.floor(diff / 365 / 24 / 60 / 60 / 1000)}年前`;
      }
   };
   const [messages, setMessages] = useState([]); // 用于存储聊天消息的状态
   const [input, setInput] = useState(""); // 用于存储当前输入值的状态
   const [ws, setWs] = useState(null); // 用于存储 WebSocket 连接的状态
   const [isConnected, setIsConnected] = useState(false); // 用于跟踪连接状态的状态
   const location = useLocation();
   // 定义用户userId和friendId的状态
   const [userId, setUserId] = useState(location.state.userId);
   const [friendId, setFriendId] = useState(location.state.friendId);
   const [username, setUsername] = useState(location.state.username);
   const [friendName, setFriendName] = useState(location.state.friendName);
   useEffect(() => {
      scrollToBottom();
   }, [messages]);
   // 获取聊天消息的函数
   const getMessage = async () => {
      try {
         const { code, result } = await getApi({
            url: "/message/userId",
            params: { userId, friendId },
         }); ``
         if (code === 200) {
            console.log(result, "=============================");
            setMessages(result);
         } else {
            console.log("数据获取失败");
         }
      } catch (error) {
         console.error("获取聊天消息失败:", error);
      }
   };
   // 初始化聊天消息
   useEffect(() => {
      getMessage();
   }, []);
   // 创建 WebSocket 连接
   useEffect(() => {
      // 当组件挂载时创建 WebSocket 连接
      const webSocket = new WebSocket("ws://127.0.0.1:3000");
      setWs(webSocket); // 将 WebSocket 实例存储在状态中

      // WebSocket 连接打开时的事件监听器
      webSocket.addEventListener("open", () => {
         console.log("WebSocket 连接已打开");
         setIsConnected(true); // 设置连接状态为 true
      });

      // WebSocket 错误的事件监听器
      webSocket.addEventListener("error", (error) => {
         console.error("WebSocket 错误:", error);
      });

      // WebSocket 连接关闭时的事件监听器
      webSocket.addEventListener("close", () => {
         console.log("WebSocket 连接已关闭");
         setIsConnected(false); // 设置连接状态为 false
      });

      // 处理接收到的消息的事件处理器
      webSocket.onmessage = (event) => {
         try {
            const message = event.data; // 获取消息数据
            if (typeof message !== "string") {
               console.error("消息不是字符串:", message);
               return;
            }
            // 解析 JSON 对象并获取消息数据
            const parsedMessage = JSON.parse(message);
            // 假设消息包含 type 和 content 字段
            const { type, content } = parsedMessage;

            switch (type) {
               case "Person":
                  console.log("聊天消息:", content);
                  break;
               case "heartbeat":
                  console.log("心跳消息:", content);
                  break;
               case "reminding":
                  console.log("消息更新:", content);
                  break;
               case "Notices":
                  console.log("公告信息:", content);
                  break;
               default:
                  console.warn("无效的消息类型:", type);
                  break;
            }
            if (type === "Person" || type === "heartbeat" || type === "reminding" || type === "Notices") {
               // 如果消息类型有效
               getMessage();
            }
         } catch (error) {
            console.error("解析消息时出错:", error); // 记录任何解析错误
         }
      };

      // 清理函数，在组件卸载时关闭 WebSocket
      return () => {
         webSocket.close();
      };
   }, []);
   // 通过 WebSocket 发送消息的函数
   const sendMessage = useCallback(() => {
      if (ws && input) {
         // 检查 WebSocket 连接是否存在且输入不为空
         let obj = { type: "Person", userId, friendId, content: input };
         ws.send(JSON.stringify(obj)); // 发送输入的消息
         setInput(""); // 清空输入框
         getMessage(); // 获取并更新聊天消息
      }
   }, [ws, input]);

   // 处理键盘按下事件的事件处理器
   const handleKeyDown = (e) => {
      if (e.key === "Enter") {
         // 检查是否按下了 Enter 键
         sendMessage(); // 调用发送消息的函数
      }
   };
   // 定义一个函数用来滚动到底部
   const scrollToBottom = useCallback(() => {
      const chatroomBodyList = document.querySelector(".chatroom-body-List");
      chatroomBodyList.scrollTop = chatroomBodyList.scrollHeight;
   }, []);
   // 定义一个表情包数组
   const faceList = [
      { src: "./img/emoji/1f60a.png", alt: "😊" },
      { src: "./img/emoji/1f60e.png", alt: "😎" },
      { src: "./img/emoji/1f61f.png", alt: "😟" },
      { src: "./img/emoji/1f622.png", alt: "😢" },
      { src: "./img/emoji/1f631.png", alt: "😱" },
      { src: "./img/emoji/1f638.png", alt: "😸" },
      { src: "./img/emoji/1f64c.png", alt: "😌" },
      { src: "./img/emoji/1f64f.png", alt: "👏" },
      { src: "./img/emoji/1f64a.png", alt: "👋" },
      { src: "./img/emoji/1f64d.png", alt: "🙏" },
      { src: "./img/emoji/1f64e.png", alt: "🤝" },
      { src: "./img/emoji/1f64f.png", alt: "👏" },
      { src: "./img/emoji/1f64b.png", alt: "🤝" },
      { src: "./img/emoji/1f654.png", alt: "🤔" },
      { src: "./img/emoji/1f655.png", alt: "🤕" },
      { src: "./img/emoji/1f656.png", alt: "🤖" },
      { src: "./img/emoji/1f657.png", alt: "🤗" },
      { src: "./img/emoji/1f658.png", alt: "🤘" },
      { src: "./img/emoji/1f659.png", alt: "🤙" },
      { src: "./img/emoji/1f65a.png", alt: "🤚" },
      { src: "./img/emoji/1f65b.png", alt: "🤛" },
      { src: "./img/emoji/1f65c.png", alt: "🤜" },
      { src: "./img/emoji/1f65d.png", alt: "🤝" },
      { src: "./img/emoji/1f65e.png", alt: "🤞" },
      { src: "./img/emoji/1f65f.png", alt: "👏" },
      { src: "./img/emoji/1f660.png", alt: "🤞" },
      { src: "./img/emoji/1f661.png", alt: "🤠" },
      { src: "./img/emoji/1f662.png", alt: "🤡" },
      { src: "./img/emoji/1f663.png", alt: "🤣" },
   ];
   // 定义一个变量用来控制打开表情的盒子
   const [showFaceBox, setShowFaceBox] = useState(false);
   // 定义一个变量用来记录所点击的表情图片
   const [faceImage, setFaceImage] = useState(null);
   // 定义一个函数用来插入表情到输入框
   const insertFace = useCallback(
      (face) => {
         if (input) {
            setInput(input.slice(0, input.length - 1) + face); // 在输入框中插入表情
         } else {
            setFaceImage(face); // 记录所点击的表情图片
         }
      },
      [input]
   );
   return (
      <>
         <div className='chatroom'>
            <div className='chatroom-header'>
               <div className='chatroom-header-item' onClick={() => navigate(-1)}>
                  <LeftOutline />
               </div>
               <div className='chatroom-header-item1'>
                  {friendName}
                  <i className='iconfont icon-shengdanye' style={{ color: "red" }}></i>
               </div>
            </div>
            <div className='chatroom-body'>
               <div className='chatroom-body-List'>
                  {messages.map((item, index) =>
                     item.userId._id == userId ? (
                        <div className='chatroom-body-List-item' key={item._id}>
                           <div style={{ width: "100%", textAlign: "center", padding: "10px 0 0 0" }}>{relativeDate(item.time)}</div>
                           <div className='chatroom-body-List-item-d1' style={{ justifyContent: "right" }}>
                              <div
                                 style={{
                                    maxWidth: "70%",
                                    marginTop: "20px",
                                    marginRight: "10px",
                                    borderRadius: "20px",
                                    padding: "10px",
                                    boxSizing: "border-box",
                                    background: "#dce8ff",
                                 }}
                              >
                                 <p style={{ marginLeft: "10px" }} className='chatroom-body-List-item-text'>
                                    {item.content}
                                 </p>
                              </div>
                              <div style={{ display: "flex", alignItems: "center", marginTop: "25px" }}>
                                 <div className='chatroom-body-List-item-icon'>
                                    <div>
                                       <img style={{ borderRadius: "50px", width: "50px", height: "50px" }} src={item.userId.avatar} alt='' />
                                    </div>
                                 </div>
                              </div>
                           </div>
                        </div>
                     ) : (
                        <div className='chatroom-body-List-item' key={item._id}>
                           <div style={{ width: "100%", textAlign: "center", padding: "10px 0 0 0" }}>{relativeDate(item.time)}</div>
                           <div className='chatroom-body-List-item-d1'>
                              <div style={{ display: "flex", alignItems: "center", marginTop: "25px" }}>
                                 <div className='chatroom-body-List-item-icon'>
                                    <div>
                                       <img style={{ borderRadius: "50px", width: "50px", height: "50px" }} src={item.userId.avatar} alt='' />
                                    </div>
                                 </div>
                              </div>
                              <div
                                 style={{
                                    maxWidth: "70%",
                                    marginLeft: "10px",
                                    marginTop: "20px",
                                    borderRadius: "20px",
                                    padding: "10px",
                                    boxSizing: "border-box",
                                    background: "#ffffff",
                                 }}
                              >
                                 <p className='chatroom-body-List-item-text'>{item.content}</p>
                              </div>
                           </div>
                        </div>
                     )
                  )}
               </div>
            </div>
            <div className='chatroom-footer'>
               <div className='chatroom-footer-item'>
                  <div className='chatroom-footer-item-1'>
                     <Input placeholder='发消息...' value={input} onChange={(e) => setInput(e)} onKeyDown={handleKeyDown} />
                  </div>
                  <div className='chatroom-footer-item-2'>
                     <i
                        className={["iconfont", showFaceBox ? "icon-w_jianpan" : "icon-xiaolian"].join(" ")}
                        style={{ padding: "0px 6px", color: "black" }}
                        onClick={() => setShowFaceBox(!showFaceBox)}
                     ></i>
                     <span onClick={() => (sendMessage(), setShowFaceBox(!showFaceBox))}>发送</span>
                  </div>
               </div>
               <div className='chatroom-footer-item2' style={{ display: showFaceBox ? "block" : "none", width: "100vw", height: "200px", background: "#ffffff" }}>
                  <div style={{ display: "flex", flexWrap: "wrap", height: "100%", padding: "10px", overflow: "auto" }}>
                     {faceList.map((item, index) => (
                        // <img key={index} alt={item.alt} style={{ width: "30px", height: "30px", cursor: "pointer" }} onClick={() => setInput(input + item.alt)} />
                        <div key={index} style={{ width: "50px", height: "50px", cursor: "pointer", textAlign: "center", marginLeft: "2px" }}>
                           <div style={{ width: "100%", height: "100%", fontSize: "20px" }} onClick={() => setInput(input + item.alt)}>
                              {item.alt}
                           </div>
                        </div>
                     ))}
                  </div>
               </div>
            </div>
         </div>
      </>
   );
}
